package address

import (
	"context"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/jwt"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/forum/api/internal/utils/parse"
	"mall/service/user/rpc/userclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetUserAddressListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 获取UserAddress列表
func NewGetUserAddressListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserAddressListLogic {
	return &GetUserAddressListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetUserAddressListLogic) GetUserAddressList(
	req *types.GetUserAddressListReq,
	headers *[]*types.Header,
) (resp *types.GetUserAddressListResp, err error) {
	userId := jwt.GetUserId(l.ctx)
	if userId == 0 {
		return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	}

	page, pageSize := parse.ParsePageInfo(
		req.Current,
		req.PageSize,
		l.svcCtx.Config.Query.DefaultAmount,
		l.svcCtx.Config.Query.MaxAmount,
	)

	preload := "userAddress:Id,Consignee,Mobile,Province,City,District,DetailedAddress,PostalCode,IsDefault"
	eagerLoad := "userAddress:total"
	// 构造查询条件
	var filters []string
	filters = append(filters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.StatusEnabled), 10))
	filters = append(filters, "UserId,equalTo:"+strconv.FormatInt(int64(userId), 10))

	res, err := l.svcCtx.UserRpc.GetUserAddressList(l.ctx, &userclient.BaseListReq{
		Offset:     uint32((page - 1) * pageSize),
		Limit:      uint32(pageSize),
		Preload:    pointy.GetPointer(preload),
		EagerLoad:  pointy.GetPointer(eagerLoad),
		Filter:     pointy.GetPointer(strings.Join(filters, ";")),
		VisitorId:  pointy.GetPointer(userId),
		PlatformId: pointy.GetPointer(globalkey.ThirdPartyPlatformWechatMini),
	})
	if err != nil {
		return nil, err
	}

	var hasNextPage bool
	var hasPreviousPage bool
	if res.HasNextPage != nil && *res.HasNextPage > 0 {
		hasNextPage = true
	}
	if res.HasPreviousPage != nil && *res.HasPreviousPage > 0 {
		hasPreviousPage = true
	}

	resp = &types.GetUserAddressListResp{
		BaseListInfo: types.BaseListInfo{
			Total:           res.Total,
			HasNextPage:     hasNextPage,
			HasPreviousPage: hasPreviousPage,
		},
	}

	if len(res.List) > 0 {
		for _, v := range res.List {
			resp.List = append(resp.List, &types.UserAddressInfo{
				Id:              v.Id,
				Label:           v.Label,
				Consignee:       v.Consignee,
				Mobile:          v.Mobile,
				Province:        v.Province,
				City:            v.City,
				District:        v.District,
				Street:          v.Street,
				DetailedAddress: v.DetailedAddress,
				PostalCode:      v.PostalCode,
				RegionCode:      v.RegionCode,
				IsDefault:       v.IsDefault,
			})
		}
	}

	*headers = []*types.Header{
		{
			Key:   "x-class",
			Value: "com.djx.appview.UserAddressPage",
		},
	}

	return resp, nil
}
